package xty.mongodb.controller;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xty.user.entity.Student;
import xty.user.entity.User;
import xty.user.service.IMongoStudentService;
import xty.user.service.IMongoUserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by XieTianYi on 2019/12/18.
 */
@RestController
@RequestMapping("mongo/user")
public class MongoUserController {

    @Resource
    private IMongoUserService mongoUserService;

    @RequestMapping("save")
    public String save(User user) {

        List<Student> students = mongoStudentService.find(new Query());
        user.setStudents(students);

        if (user.getId() == null) {
            mongoUserService.save(user);
        } else {
            mongoUserService.update(user);
        }
        return "成功";
    }

    @RequestMapping("list")
    public JSON list() {
        //
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.lookup("student", "_id", "fId", "fff"),
                Aggregation.sort(new Sort(Sort.Direction.DESC,"name"))
        );

        List users = mongoUserService.find(aggregation);
        return JSONArray.fromObject(users);
    }

    @Resource
    private IMongoStudentService mongoStudentService;

    @RequestMapping("list2")
    public JSON list2() {

        List<Student> students = mongoStudentService.find(new Query());
        return JSONArray.fromObject(students);
    }

    @RequestMapping("delete")
    public String delete(String[] ids) {
        mongoUserService.delete(ids);
        return "成功";
    }
}